import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(RootApp());

// 定义根目录Wigdget
class RootApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 根视图
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.grey[200]),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  PageController _pageController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _pageController = new PageController(initialPage: 1000);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      startTimer();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  // 定时器
  Timer _timer;
  void startTimer() {
    _timer = new Timer.periodic(Duration(milliseconds: 2000), (value) {
      currentIndex++;
      _pageController.animateToPage(currentIndex,
          duration: Duration(milliseconds: 200), curve: Curves.ease);
      if (currentIndex >= 1000) {
        currentIndex = 0;
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('banner'),
        ),
        body: buildBanner());
  }

  buildBanner() {
    return Container(
      height: 200,
      width: double.infinity,
      child: Stack(
        children: [
          // 轮播照片
          buildBannerWidget(),
          // 指示器
          buildTipsWidget()
        ],
      ),
    );
  }

  // 轮播照片
  List list = [
    'images/3.0/logo.jpg',
    'images/3.0/logo.jpg',
    'images/3.0/logo.jpg',
    'images/3.0/logo.jpg',
  ];
  int currentIndex = 500;
  buildBannerWidget() {
    return PageView.builder(
        controller: _pageController,
        itemBuilder: (BuildContext context, int index) {
          return buildPageViewItemWidget(index);
        },
        itemCount: list.length * 1000,
        onPageChanged: (value) {
          setState(() {
            currentIndex = value;
          });
        });
  }

  buildPageViewItemWidget(int index) {
    return Image.asset(list[index % list.length], fit: BoxFit.fill);
  }

  // 指示器
  buildTipsWidget() {
    return Positioned(
      bottom: 10,
      right: 20,
      child: Container(
        padding: EdgeInsets.only(top: 2, bottom: 2, left: 8, right: 8),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(
            Radius.circular(10),
          ),
        ),
        child: Text("${currentIndex % list.length + 1}/${list.length}"),
      ),
    );
  }
}
